import './index.scss'
import React, { useState, useEffect, useRef } from 'react'
import { useStore } from 'react-redux'
import { useHistory, useLocation } from 'react-router-dom';
import { Steps, Button, Form, Input, Select, notification } from 'antd';
import MyEditor from '../../components/Editor'
import http from '../../api'

const steps = [
    {
        title: '基本信息',
        description: '新闻标题，新闻分类'
    },
    {
        title: '新闻内容',
        description: '新闻主题内容'
    },
    {
        title: '新闻提交',
        description: '保存草稿或者提交审核'
    }
]

export default function NewsAdd() {
    const [current, setCurrent] = useState(0);
    const [newsClassify, setNewsClassify] = useState([])
    const [isEdit, setIsEdit] = useState(false)
    const [formInfo, setFormInfo] = useState({})
    const [content, setContent] = useState('')
    const { UserInfo } = useStore().getState()
    const formRef = useRef(null)
    const history = useHistory()
    const location = useLocation()

    useEffect(() => {
        setCurrent(0)
        getNewsClassify()

        if (location.state) {
            setIsEdit(true)
            setFormInfo(location.state)
            setContent(location.state.content)
            formRef.current.setFieldsValue(location.state)
        } else {
            setFormInfo({})
            setContent(false)
        }
    }, [])


    const getNewsClassify = () => {
        http.get('/categories').then(res => {
            setNewsClassify(res.data)
        })
    }

    //上一步下一步
    const operBtnClick = (type) => {
        if (type === 'next') {
            current === 0 && formRef.current.validateFields().then(res => {
                setFormInfo(res)
                setCurrent(current + 1);
            }).catch(err => { })
            current === 1 && content && setCurrent(current + 1);
        } else if (type === 'last') {
            setCurrent(current - 1);
        }
    }

    //提交审核或保存草稿
    const save = (auditState) => {
        const data =
        {
            ...formInfo,
            "content": content,
            "region": UserInfo.region ? UserInfo.region : '全球',
            "author": UserInfo.username,
            "roleId": UserInfo.roleId,
            "auditState": auditState, // 0-草稿箱、1-待审核、2-已审核、3-驳回
            "publishState": 0,
            "createTime": Date.now(),
            "star": 0,
            "view": 0,
        }
        const api = isEdit ? http.patch(`/news/${location.state.id}`, data) : http.post('/news', data)
        api.then(res => {
            history.push(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
            notification.success({
                message: `${auditState === 0 ? '保存' : '提交'}成功`,
                description: `您可以到${auditState === 0 ? '【新闻管理/草稿箱】' : '【审核管理/审核列表】'}中查看您的新闻`,
                placement: 'bottomRight'
            });
        })
    }

    //通过绑定函数拿取富文本编辑器里的内容
    const getNewsContent = (content) => {
        setContent(JSON.stringify(content))
    }

    return (
        <div className='news-add-box'>
            <h1>撰写新闻</h1>
            {/* 进度条 */}
            <Steps current={current} items={steps} />
            {/* 新闻标题，新闻分类 */}
            <div>
                <Form
                    className={`title-box ${current === 0 ? '' : 'hiden'}`}
                    ref={formRef}
                    name="basic"
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                >
                    <Form.Item
                        label="新闻标题"
                        name="title"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your title!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="新闻分类"
                        name="categoryId"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your categoryId!',
                            },
                        ]}
                    >
                        <Select>
                            {newsClassify.map(item => <Select.Option key={item.value} value={item.id}>{item.title}</Select.Option>)}
                        </Select>
                    </Form.Item>
                </Form>
                <div className={current === 1 ? '' : 'hiden'}>
                    <MyEditor getNewsContent={getNewsContent} content={content} />
                </div>
            </div>
            <div className='btn-box'>
                <Button type='primary' className={`${current === 2 ? 'hiden' : ''}`} onClick={() => operBtnClick('next')}>下一步</Button>
                <Button type='primary' className={`${current === 0 ? 'hiden' : ''}`} onClick={() => operBtnClick('last')}>上一步</Button>
                <Button type='primary' className={`${current === 2 ? '' : 'hiden'}`} onClick={() => save(0)}>保存草稿</Button>
                <Button type='primary' className={`${current === 2 ? '' : 'hiden'}`} onClick={() => save(1)}>提交审核</Button>
            </div>
        </div>
    )
}